﻿using UnityEngine;
using System.Collections;

public class MainLoop : MonoBehaviour {

    public GameObject BlackPrefab;
    public GameObject WhitePrefab;

    public ResultWindows _result;

    enum State
    { 
        BlackGO,
        WhiteGO,
        Over,
    }

    State _state;

    Board _board;

    BoardModel _model;

    AI _ai;

    bool CanPlace(int gridX, int gridY)
    {
        return _model.Get(gridX, gridY) == ChessType.None;
    }

    bool PlaceChess(Cross cross, bool isBlack)
    {
        if (cross==null)
        {
            return false;
        }

        GameObject newCress = GameObject.Instantiate(isBlack?BlackPrefab:WhitePrefab);

        newCress.transform.SetParent(cross.transform,false);

        ChessType ctype = isBlack?ChessType.Black:ChessType.White;

        _model.Set(cross.GridX, cross.GridY, ctype);

        int linkCount = _model.CheckLink(cross.GridX,cross.GridY,ctype);
        return linkCount>=BoardModel.WinChessCount;


    }

    public void Restart()
    {
        _state = State.BlackGO;
        _model = new BoardModel();
        _ai = new AI();
        _board.Reset();
    }

    int _lastPlayerX, _lastPlayerY;

    public void OnClick(Cross cross)
    {
        if (_state != State.BlackGO)
        {
            return;
        }
        if (CanPlace(cross.GridX,cross.GridY))
        {
            _lastPlayerX = cross.GridX;
            _lastPlayerY = cross.GridY;
        }


        if (PlaceChess(cross,true))
        {
            _state = State.Over;
            ShowResult(ChessType.Black);
        }
        else
        {
            _state = State.WhiteGO;
        }
    }
	// Use this for initialization
	void Start () {
	    _board = GetComponent<Board>();

        Restart();
	}

    void ShowResult(ChessType winside)
    {
        _result.gameObject.SetActive(true);
        _result.Show(winside);
    }
	
	// Update is called once per frame
	void Update () {
        switch (_state)
        {
            case State.BlackGO:
                break;
            case State.WhiteGO:
                int gridX, gridY;
                _ai.ComputerDo(_lastPlayerX,_lastPlayerY,out gridX,out gridY);
                if (PlaceChess(_board.GetCross(gridX,gridY),false))
                {
                    _state = State.Over;
                    ShowResult(ChessType.White);
                }
                else
                {
                    _state = State.BlackGO;
                }
                break;
            case State.Over:
                break;
            default:
                break;
        }
	}
}
